package com.example.service;

import com.example.entity.Block;
import com.example.mapper.BlockMapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

/**
 * 区块表相关服务
 */
@Service
public class BlockService {

    @Resource
    private BlockMapper blockMapper;

    /**
     * 查询表中最新的block_number
     */
    public Long getLatestBlockNumber() {
        // SELECT MAX(block_number) FROM tb_block
        return blockMapper.selectObjs(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Block>()
                        .select("max(block_number)")
        ).stream().findFirst().map(o -> o == null ? null : ((Number)o).longValue()).orElse(null);
    }

    /**
     * 检测区块是否重组（parent_block_hash与上一块的block_hash不一致即为重组）
     * @param block 当前区块
     * @return true=发生重组，false=未重组
     */
    public boolean isBlockReorg(Block block) {
        if (block.getBlockNumber() == null || block.getBlockNumber() <= 0) return false;
        Block prev = getBlockByNumber(block.getBlockNumber() - 1);
        if (prev == null) return false;
        return !block.getParentBlockHash().equals(prev.getBlockHash());
    }

    /**
     * 保存区块信息
     */
    public void saveBlock(Block block) {
        blockMapper.insert(block);
    }

    /**
     * 根据区块高度查询区块
     */
    public Block getBlockByNumber(Long blockNumber) {
        return blockMapper.selectById(blockNumber);
    }


}
